import 'dart:async';

import 'package:flutter/material.dart';

class TextScrollWidget extends StatefulWidget {
  final Duration duration; // 轮播时间
  final double stepOffset; // 偏移量
  final List<Widget> children; // 内容
  const TextScrollWidget({super.key, required this.duration, required this.stepOffset, required this.children});

  @override
  State<TextScrollWidget> createState() => _TextScrollWidgetState();
}

class _TextScrollWidgetState extends State<TextScrollWidget> {
  late ScrollController _controller; // 执行动画的controller
  late Timer _timer; // 定时器timer
  double _offset = 0.0; // 执行动画的偏移量

  @override
  Widget build(BuildContext context) {
    return ListView.builder(
      physics: const NeverScrollableScrollPhysics(),
      scrollDirection: Axis.vertical, //
      controller: _controller, // 滚动的controller
      itemBuilder: (context, index) {
        return Expanded(child: Row(children: widget.children));
      },
    );
  }

  @override
  void initState() {
    super.initState();
    _controller = ScrollController(initialScrollOffset: _offset);
    _timer = Timer.periodic(widget.duration, (timer) {
      double newOffset = _controller.offset + widget.stepOffset;
      if (newOffset != _offset) {
        _offset = newOffset;
        _controller.animateTo(_offset, duration: widget.duration, curve: Curves.linear); // 线性曲线动画
      }
    });
  }

  @override
  void dispose() {
    _timer.cancel();
    _controller.dispose();
    super.dispose();
  }
}
